#include "grpceventdispatchercore.h"

#include "grpceventserverservice.h"
#include "grpceventdef.h"
#include "nlohmann/jsonwrapper.h"

#include <QDebug>
std::shared_ptr<GrpcEventDispatcherCore> g_pEventDispatcher = nullptr;
GrpcEventDispatcherCore::GrpcEventDispatcherCore(QObject* parent)
    :QObject(parent)
{
    m_waitToGo[1000].push_back("LiXinJi");
    m_waitToGo[1000].push_back("MCU2");

    m_waitToGo[1001].push_back("MCU3");
    m_waitToGo[1001].push_back("MCU1");

    m_waitToGo[1002].push_back("LiXinJi");
    m_waitToGo[1002].push_back("MCU3");

    m_waitToGo[1003].push_back("LiXinJi");
    m_waitToGo[1003].push_back("MCU1");

    connect(&m_timer, &QTimer::timeout, this, [this](){
        if(!m_waitSend.empty())
        {
            const GrpcEventJsonAvis& data = m_waitSend.front();
            nlohmann::json json = data;
            g_pEventService->SendEvent(data.TargetId, json.dump());
            m_waitSend.pop();
        }

    });

    m_timer.start(1000);
}

void GrpcEventDispatcherCore::DispatchLocal(const std::string &jsonText)
{
    qDebug() << "recv " << jsonText.c_str();
    std::pair<GrpcEventJsonAvis, bool> ret = ParseFromString<GrpcEventJsonAvis>(jsonText);
    if(ret.second)
    {
        if("SMB" != ret.first.TargetId) //转发
        {
            g_pEventService->SendEvent(ret.first.TargetId, jsonText);
        }
        else
        {
            if(ret.first.EventName == ReqShelfTask)
            {
                ShelfInfoParam recvParam;
                if(recvParam.ParseFromJsonArray(ret.first.Parameters))
                {
                    ResShelfTaskParam sendParam;
                    sendParam.shelfNum = recvParam.ulShelfNum;
                    sendParam.waitToGo = m_waitToGo[recvParam.ulShelfNum];

                    GrpcEventJsonAvis event;
                    event.SourceId = "SMB";
                    event.TargetId = ret.first.SourceId;
                    event.EventName = ResShelfTask;
                    //由于c# 那边是数组。。。
                    event.Parameters = sendParam.SerializeToJsonArray();

                    m_waitSend.push(event);
                }

            }


        }

    }

}

void GrpcEventDispatcherCore::DispatchRemote(const std::string& eventName, EventParamNull* param,
                                             std::string dst, std::string src)
{
    GrpcEventJsonAvis event;
    event.SourceId = src;
    event.TargetId = dst;
    event.EventName = eventName;
    //由于c# 那边是数组。。。
    event.Parameters = param->SerializeToJsonArray();
    nlohmann::json json = event;

    g_pEventService->SendEvent(dst, json.dump());
}
